//
//  DesSearchedVC.m
//  HappyTrip
//
//  Created by yuxuesong on 15-4-2.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "DesSearchedVC.h"
#import "DesTripsObject.h"
#import "DestinationTripTableViewCell.h"
#import "TravelNoteViewController.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"
#import "DesSearchVC.h"

#define TRIPSIdentifier @"tripsTableViewCellReuse"

@interface DesSearchedVC () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>

@property (nonatomic, retain) NSMutableArray *tripsArr;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) MBProgressHUD *progressHUD;

@end

@implementation DesSearchedVC

- (void)dealloc
{
    [_tripsArr release];
    [_tableView release];
    [_progressHUD release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.title = @"搜索结果";
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:170.0 / 255.0 blue:205.0 / 255.0 alpha:1.0];
    self.tabBarController.tabBar.hidden = NO;
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tripsArr = [NSMutableArray array];
    [self handleData:0];
    [self setupViews];
    
}
#pragma mark - 建立视图
- (void)setupViews
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT) style:UITableViewStylePlain];
//    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    [_tableView registerClass:[DestinationTripTableViewCell class] forCellReuseIdentifier:TRIPSIdentifier];
    [self.view addSubview:_tableView];
    [_tableView release];
    
    //转菊花
    self.progressHUD = [[MBProgressHUD alloc] initWithView:self.tableView];
    _progressHUD.labelText = @"请稍等...";
    _progressHUD.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_progressHUD];
    [_progressHUD release];
    [_progressHUD show:YES];
    
//    刷新加载
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [_tableView.header endRefreshing];
    }];
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        static NSInteger i = 1;
        [self handleData:i++ * 20];
    }];

}
#pragma mark - tableView 的协议方法们
//--------- cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tripsArr.count;
}
//--------- cell 中的数据处理
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DestinationTripTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TRIPSIdentifier];
    cell.desTripsObject = [_tripsArr objectAtIndex:indexPath.row];
    cell.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (VIEW_HEIGHT + 64 + 49) / 4;
}
//--------- 点击 cell 推出下一页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelNoteViewController *travelVC = [[TravelNoteViewController alloc] init];
    DesTripsObject *desTrips = [_tripsArr objectAtIndex:indexPath.row];
    travelVC.transmitId = [desTrips.idNumber stringValue];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.navigationController pushViewController:travelVC animated:YES];
    [travelVC release];
}

//--------- 返回按钮
- (void)leftBarButtonItemAction:(UIBarButtonItem *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 数据解析
- (void)handleData:(NSInteger)number
{
    NSString *urlStr = [NSString stringWithFormat:@"http://api.breadtrip.com/search/?key=%@&start=%ld&count=20&source=search", self.searchSendKey, number];
    urlStr = [urlStr  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%ld.happyTrip", docPath, [urlStr hash]];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:path];
        NSLog(@"存储成功: %d", result);
        NSMutableArray *arr = [responseObject objectForKey:@"trips"];
        if (0 == arr.count || [self.searchSendKey isEqualToString:nil]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"对不起,暂无相关信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        }
        for (NSMutableDictionary *dic in arr) {
            DesTripsObject *tripsObj = [[DesTripsObject alloc] initWithDic:dic];
            [self.tripsArr addObject:tripsObj];
            [tripsObj release];
        }
        [_tableView reloadData];
        [_progressHUD removeFromSuperview];
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        id resultID = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
//        static NSInteger i = 1;
//        if (1 == i) {
//            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络不给力,请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alertView show];
//            [alertView release];
//        }
//        i++;
        
        NSMutableArray *arr = [resultID objectForKey:@"trips"];
        if (0 == arr.count || [self.searchSendKey isEqualToString:nil]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"对不起,暂无相关信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        }
        for (NSMutableDictionary *dic in arr) {
            DesTripsObject *tripsObj = [[DesTripsObject alloc] initWithDic:dic];
            [self.tripsArr addObject:tripsObj];
            [tripsObj release];
        }
        [_tableView reloadData];
        [_progressHUD removeFromSuperview];
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
    }];
}


- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    DesSearchVC *searchVC = [[DesSearchVC alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
